/*
 * 文件名：TokenAuthenticationInterceptor.java
 * 版权：MoonBox 
 * 修改人：Peter
 * 修改时间：2018年10月10日
 * 修改内容：新增
 */
package com.renzhebiao.lkang.Interceptor;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.renzhebiao.lkang.comment.Need;
import com.renzhebiao.lkang.exception.ForbiddenException;
import com.renzhebiao.lkang.request.RequestCache;
import com.renzhebiao.lkang.request.RequestPayload;
import com.renzhebiao.lkang.token.JwtTokenUtil;

import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;

/**
 * TODO 添加类的一句话简单描述。
 * <p>
 * TODO 详细描述
 * 
 * @author Peter
 * @since 1.0.0
 */
@Log4j
public class TokenAuthenticationInterceptor extends HandlerInterceptorAdapter {

    private Map<String, Object> map;
    private final String        TOKEN_EXPIRE = "token 过期";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        JwtTokenUtil jwt = new JwtTokenUtil();
        Need need = handlerMethod.getMethod().getAnnotation(Need.class);
        if (need != null && need.token() == true) {
            RequestPayload payload = RequestCache.get();
            map = jwt.getClaimsFromToken(payload.getToken());
            int id = (int) map.get("id");
            payload.setUserId(Long.valueOf(id));
            Date date = new Date(Long.valueOf((int) map.get(Claims.EXPIRATION)));
            validTime(date);
            // validIp(token.getIp(), token.getIp());//可以从缓存中拿取ip进行判断
        }
        return true;
    }

    /**
     * 判断过期时间
     * 
     * @param time
     */
    private void validTime(Date time) {
        if (time != null && time.getTime() * 1000 < System.currentTimeMillis()) {
            throw new ForbiddenException(TOKEN_EXPIRE);
        }
    }

    // private void validIp(String ip, String reqIp) {
    // if (!ip.equals(reqIp)) {
    // log.error("token Ip校验失败");
    // throw new ForbiddenException(StatusCode.Forbidden.TOKEN_INVALID);
    // }
    // }

}
